package com.dt.common.validation.parser;

import java.lang.reflect.Field;

import com.alibaba.fastjson.JSONObject;
import com.dt.common.validation.annotation.Size;
import com.dt.common.validation.definition.SizeDefinition;
import com.dt.common.validation.exception.BuildingException;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.PropertyGetter;

public class SizeDefinitionParser extends DefinitionParser {

	@Override
	public DefaultValidationDefinition parseFromAnnotation(Field field, PropertyGetter propertyGetter) {
		Size size = field.getAnnotation(Size.class);
		if (size != null) {
			int min = size.min();
			int max = size.max();
			String msg = size.msg();

			return buildDefinition(min, max, msg);
		}
		return null;
	}

	private DefaultValidationDefinition buildDefinition(int min, int max, String msg) {
		if (min < 0 || max < 0) {
			throw new BuildingException("property min and max can't less than 0.");
		}
		if (min > max) {
			throw new BuildingException("property min can't greatter than max.");
		}

		SizeDefinition definition = new SizeDefinition();
		definition.setMax(max);
		definition.setMin(min);
		definition.setRawMsg(msg);

		return definition;
	}

	@Override
	public DefaultValidationDefinition parseFromJson(JSONObject metaValues) {
		Integer min = metaValues.getInteger("min");
		Integer max = metaValues.getInteger("max");
		if (min == null || max == null) {
			throw new BuildingException("Size min and max must defined.");
		}
		String msg = this.getMsgDefinition(metaValues, true);
		return buildDefinition(min, max, msg);
	}

}
